
const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    moveNode: cc.Node = null;

    @property
    speed: number = 0;

    @property(cc.Component.EventHandler)
    func: cc.Component.EventHandler = null;

    joyStickBtn: cc.Node = null;
    dir: cc.Vec2;


    onLoad() {
        //cc.Button.EventHandler.bind
        cc.debug.setDisplayStats(false);
        this.joyStickBtn = this.node.children[0];

        let coll = cc.director.getCollisionManager();
        coll.enabled = true;
        //coll.enabledDebugDraw=true;

        this.dir = cc.v2(0, 0);


    }
    start() {
        // touch event
        this.node.on('touchstart', this.onTouchStart, this);
        this.node.on('touchmove', this.onTouchMove, this);
        this.node.on('touchend', this.onTouchEnd, this);
        this.node.on('touchcancel', this.onTouchCance, this);
    }

    onDestroy(){
        this.node.off('touchstart', this.onTouchStart, this);
        this.node.off('touchmove', this.onTouchMove, this);
        this.node.off('touchend', this.onTouchEnd, this);
        this.node.off('touchcancel', this.onTouchCance, this);
    }

    update(dt) {

        //控制滚轮的半径不能越界
        let len = this.joyStickBtn.position.mag();      //长度
        let radius = this.node.width / 2;               //半径
        let ratio = len / radius;                       //比值
        // 半径不能越界
        if (ratio > 1) {
            this.joyStickBtn.position = this.joyStickBtn.position.div(ratio);
        }

        //移动
        if (this.moveNode) {
            let dis = this.dir.mul(this.speed * ratio * dt);
            let newPos = cc.v2(this.moveNode.position).add(dis);
            //阻止越界
            // if(this.node.getBoundingBox().contains(newPos)){
            //     this.moveNode.position=cc.v3(newPos);
            // }
            this.moveNode.position = cc.v3(newPos);
        }
    }

    onTouchStart(event: cc.Event.EventTouch) {
        let pos = this.node.convertToNodeSpaceAR(event.getLocation());
        this.joyStickBtn.position = cc.v3(pos);

    }

    onTouchMove(event: cc.Event.EventTouch) {
        let posDelta = event.getDelta();
        this.joyStickBtn.setPosition(this.joyStickBtn.position.add(cc.v3(posDelta)));
        // get direction
        this.dir = cc.v2(this.joyStickBtn.position.normalize());
        //发送移动回调
        this.func.emit([this.dir]);
    }

    onTouchEnd(event: cc.Event.EventTouch) {
        this.joyStickBtn.position = cc.v3();
    }

    onTouchCance(event: cc.Event.EventTouch) {
        this.joyStickBtn.position = cc.v3();
    }
}
